import apiClient from './api'

// 用户认证相关的类型定义
export interface UserLogin {
  username: string
  password: string
}

export interface UserRegister {
  username: string
  email: string
  password: string
  full_name?: string
  role?: string
}

export interface UserResponse {
  id: string
  username: string
  email: string
  full_name?: string
  role: string
  is_active: boolean
  created_at: string
}

export interface Token {
  access_token: string
  token_type: string
}

export interface LoginResponse extends Token {
  user?: UserResponse
}

// 用户认证API服务
export const authApi = {
  // 用户登录
  login: async (credentials: UserLogin): Promise<LoginResponse> => {
    // FastAPI OAuth2PasswordRequestForm 需要 form-data 格式
    const formData = new FormData()
    formData.append('username', credentials.username)
    formData.append('password', credentials.password)
    
    const response = await fetch('/api/v1/auth/login', {
      method: 'POST',
      body: formData,
    })
    
    if (!response.ok) {
      const error = await response.json()
      throw new Error(error.detail || '登录失败')
    }
    
    const result = await response.json()
    
    // 保存token到localStorage
    if (result.access_token) {
      localStorage.setItem('access_token', result.access_token)
      localStorage.setItem('token_type', result.token_type)
    }
    
    return result
  },

  // 用户注册
  register: (userData: UserRegister): Promise<UserResponse> => {
    return apiClient.post('/auth/register', userData)
  },

  // 退出登录
  logout: (): void => {
    localStorage.removeItem('access_token')
    localStorage.removeItem('token_type')
    localStorage.removeItem('current_user')
  },

  // 获取当前用户信息
  getCurrentUser: (): Promise<UserResponse> => {
    return apiClient.get('/auth/me')
  },

  // 检查token是否有效
  verifyToken: (): Promise<UserResponse> => {
    return apiClient.get('/auth/verify')
  },

  // 刷新token
  refreshToken: (): Promise<Token> => {
    return apiClient.post('/auth/refresh')
  },

  // 修改密码
  changePassword: (data: {
    current_password: string
    new_password: string
  }): Promise<{ message: string }> => {
    return apiClient.post('/auth/change-password', data)
  },

  // 更新用户信息
  updateProfile: (data: Partial<UserRegister>): Promise<UserResponse> => {
    return apiClient.put('/auth/profile', data)
  },
}

// 工具函数
export const authUtils = {
  // 检查是否已登录
  isAuthenticated: (): boolean => {
    const token = localStorage.getItem('access_token')
    return !!token
  },

  // 获取token
  getToken: (): string | null => {
    return localStorage.getItem('access_token')
  },

  // 获取token类型
  getTokenType: (): string => {
    return localStorage.getItem('token_type') || 'Bearer'
  },

  // 检查用户角色
  hasRole: (requiredRole: string): boolean => {
    const userStr = localStorage.getItem('current_user')
    if (!userStr) return false
    
    try {
      const user = JSON.parse(userStr)
      return user.role === requiredRole || user.role === 'admin'
    } catch {
      return false
    }
  },

  // 检查是否为管理员
  isAdmin: (): boolean => {
    return authUtils.hasRole('admin')
  },

  // 保存用户信息
  saveUser: (user: UserResponse): void => {
    localStorage.setItem('current_user', JSON.stringify(user))
  },

  // 获取用户信息
  getUser: (): UserResponse | null => {
    const userStr = localStorage.getItem('current_user')
    if (!userStr) return null
    
    try {
      return JSON.parse(userStr)
    } catch {
      return null
    }
  },

  // 退出登录
  logout: (): void => {
    localStorage.removeItem('access_token')
    localStorage.removeItem('token_type')
    localStorage.removeItem('current_user')
  },
}